package database;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

/**
 * 设置连接属性，返回连接对象
 */
public class DBConnect {

    private static volatile DBConnect instance = null;
    private static final String DB = "cpt304a1";
    private static final String username = "root";
    private static final String password = "password";
    private Connection connection = null;

    private DBConnect() {

    }

    public static DBConnect getInstance() {
        if (instance == null) {
            synchronized (DBConnect.class) {
                if (instance == null) {
                    instance = new DBConnect();
                }
            }
        }
        return instance;
    }

    public Connection getConnect() {
        try {
            if (connection == null || connection.isClosed()) {
                Class.forName("com.mysql.cj.jdbc.Driver");
                String url = String.format("jdbc:mysql://localhost:3306/%s?useUnicode=true&characterEncoding=utf8&useSSL=false", DB);
                connection = DriverManager.getConnection(url, username, password);
            }
        } catch (ClassNotFoundException | SQLException e) {
            e.printStackTrace();
        }
        return connection;
    }

    public void closeConnection() {
        try {
            if (connection != null) {
                connection.close();
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}
package database;

import Book.AcademicBook;
import Book.Book;
import Book.Magzine;
import User.Student;
import User.Teacher;
import User.User;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.time.LocalDate;
import java.time.temporal.ChronoUnit;

public class BookDatabase {
    public static boolean checkBook(String bookname) {
        boolean flag = false;
        ResultSet resultSet;
        PreparedStatement prestmt;
        try {
            String sql = "SELECT * FROM book WHERE bookname = ?";
            prestmt = DBConnect.getInstance().getConnect().prepareStatement(sql);
            prestmt.setString(1, bookname);
            resultSet = prestmt.executeQuery();
            if (resultSet.next()) {
                flag = true;
            }
            resultSet.close();
            prestmt.close();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return flag;
    }

    public static boolean  addBooks(String bookname,String type) {
        if(checkBook(bookname)) {
            System.out.println("Book already exists");
            return false;
        }else{
            PreparedStatement preparedStatement;
            String sql;
            try {
                sql = "insert into book (bookname,status,type,dailyfine) values(?,?,?,?)";
                preparedStatement = DBConnect.getInstance().getConnect().prepareStatement(sql);
                preparedStatement.setString(1, bookname);
                preparedStatement.setString(2, "in");
                preparedStatement.setString(3, type);
                preparedStatement.setInt(4, 15);
                int n = preparedStatement.executeUpdate();
                if (n == 1) {
                    System.out.println("Successfully added a new book");
                }
            } catch (SQLException e) {
                e.printStackTrace();
            }
            return true;
        }
    }

    public static Book checkBookStatus(String bookname) {
        ResultSet resultSet;
        PreparedStatement prestmt = null;
        Book book = null;
        java.sql.Date date = new java.sql.Date(System.currentTimeMillis());
        try {
            String sql = "SELECT * FROM book WHERE bookname = ?";
            prestmt = DBConnect.getInstance().getConnect().prepareStatement(sql);
            prestmt.setString(1, bookname);
            resultSet = prestmt.executeQuery();
            if (resultSet.next()) {
                String status = resultSet.getString("status");
                String type = resultSet.getString("type");
                if(type.equals("a")) {
                    book = new AcademicBook(bookname, date, 15,status);
                }else{
                    book = new Magzine(bookname, date, 15,status);
                }
            }else{
                System.out.println("Book does not belong to library");
            }
            resultSet.close();
            prestmt.close();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return book;
    }

    public static void borrowBook(String bookname) {
        Book book = checkBookStatus(bookname);
        if (book != null) {
            if (book.getStatus().equals("out")) {
                System.out.println("Book is already borrowed");
            } else {
                java.sql.Date currentDate = new java.sql.Date(System.currentTimeMillis());
                try {
                    // Assuming there is a column 'borrowed_on' to store the date when the book was borrowed
                    // and a column 'status' to represent if the book is in or out.
                    String sql = "UPDATE book SET status = ?, borrowdate = ? WHERE bookname = ?";
                    try (Connection conn = DBConnect.getInstance().getConnect();
                         PreparedStatement prestmt = conn.prepareStatement(sql)) {

                        prestmt.setString(1, "out");  // Set status to 'out'
                        prestmt.setDate(2, currentDate); // Set the current date as the borrow date
                        prestmt.setString(3, bookname);
                        int rowsAffected = prestmt.executeUpdate();

                        if (rowsAffected > 0) {
                            System.out.println("Book borrowed successfully");
                        } else {
                            System.out.println("Failed to update the book status");
                        }
                    }
                } catch (SQLException e) {
                    System.out.println("SQL error occurred while borrowing the book");
                    e.printStackTrace();
                }
            }
        }
    }

    public static Book returnBook(String bookname) {
        Book book = checkBookStatus(bookname);
        if (book != null) {
            if (!book.getStatus().equals("out")) {
                System.out.println("The book has been returned. Do not return it again.");
                return null; // No book returned because it's already in.
            } else {
                try {
                    String sql = "UPDATE book SET status = ? WHERE bookname = ?";
                    try (Connection conn = DBConnect.getInstance().getConnect();
                         PreparedStatement prestmt = conn.prepareStatement(sql)) {

                        prestmt.setString(1, "in");  // Set status to 'in' indicating the book is returned
                        prestmt.setString(2, bookname);
                        int rowsAffected = prestmt.executeUpdate();

                        if (rowsAffected > 0) {
                            System.out.println("Successfully returned the book.");
                            book.setStatus("in"); // Update the status in the book object to reflect the change
                            return book; // Return the book object for further processing, like calculating fines.
                        } else {
                            System.out.println("Failed to update the book status.");
                            return null; // No book returned because the update failed.
                        }
                    }
                } catch (SQLException e) {
                    System.out.println("SQL error occurred while returning the book");
                    e.printStackTrace();
                    return null; // No book returned because of an SQL error.
                }
            }
        } else {
            System.out.println("Book does not belong to library.");
            return null; // No book returned because it doesn't exist.
        }
    }

    public static void deleteBook(String bookname) {
        Book book = checkBookStatus(bookname);
        if (book != null) {
            try {
                String sql = "DELETE FROM book WHERE bookname = ?";
                try (Connection conn = DBConnect.getInstance().getConnect();
                     PreparedStatement prestmt = conn.prepareStatement(sql)) {

                    prestmt.setString(1, bookname);
                    int rowsAffected = prestmt.executeUpdate();

                    if (rowsAffected > 0) {
                        System.out.println("Book deleted successfully.");
                    } else {
                        System.out.println("Failed to delete the book.");
                    }
                }
            } catch (SQLException e) {
                System.out.println("SQL error occurred while deleting the book");
                e.printStackTrace();
            }
        } else {
            System.out.println("Book does not exist.");
        }
    }

    public static int calculateDaysBorrowed(String bookname) {
        java.sql.Date borrowDate = null;
        LocalDate today = LocalDate.now();
        int daysBorrowed = 0; // Initialize with 0

        try {
            String sql = "SELECT borrowdate FROM book WHERE bookname = ? AND status = 'out'";
            try (Connection conn = DBConnect.getInstance().getConnect();
                 PreparedStatement prestmt = conn.prepareStatement(sql)) {

                prestmt.setString(1, bookname);
                ResultSet resultSet = prestmt.executeQuery();

                if (resultSet.next()) {
                    borrowDate = resultSet.getDate("borrowdate");
                    if (borrowDate != null) {
                        daysBorrowed = (int) ChronoUnit.DAYS.between(borrowDate.toLocalDate(), today);
                    }
                }
            }
        } catch (SQLException e) {
            System.out.println("SQL error occurred while calculating days borrowed");
            e.printStackTrace();
        }

        return daysBorrowed; // Return the calculated days
    }


}

